import {
  PointerSensor,
  useSensor,
  useSensors,
  type DragStartEvent,
  type DragEndEvent,
  type DropAnimation,
  defaultDropAnimation,
  type UniqueIdentifier,
} from "@dnd-kit/core"
// import { arrayMove } from "@dnd-kit/sortable"
import { useCallback, useState } from "react"
import type { Container } from '../../types'
import { WorkStatus } from '../../types'
const DATA = [
    {
      id: "Mon",
      title: "周一",
      accepts: ["Work"],
      items: [
        { id: 'Mon-1', type: 'Work', title: 'Mon-测试工单01', content: '1.测试工单01...', times: '2h', status: WorkStatus.INPROGRESS },
        { id: 'Mon-2', type: 'Work', title: 'Mon-测试工单02', content: '1.测试工单02...', times: '3h', status: WorkStatus.COMPLETED },
        { id: 'Mon-3', type: 'Work', title: 'Mon-Tue测试工单03', content: '1.测试工单03...', times: '--', status: WorkStatus.PENDING }
      ],
    },
    {
      id: "Tue",
      title: "周二",
      accepts: ["Work"],
      items: [
        { id: 'Tue-1', type: 'Work', title: 'Tue-测试工单01', content: '1.测试工单01...', times: '2h', status: WorkStatus.INPROGRESS },
        { id: 'Tue-2', type: 'Work', title: 'Tue-测试工单02', content: '1.测试工单02...', times: '3h', status: WorkStatus.COMPLETED },
        { id: 'Tue-3', type: 'Work', title: 'Tue-测试工单03', content: '1.测试工单03...', times: '--', status: WorkStatus.PENDING }
      ],
    },
    {
      id: "Wed",
      title: "周三",
      accepts: ["Work"],
      items: [
        { id: 'Wed-1', type: 'Work', title: 'Wed-测试工单01', content: '1.测试工单01...', times: '2h', status: WorkStatus.INPROGRESS },
        { id: 'Wed-2', type: 'Work', title: 'Wed-测试工单02', content: '1.测试工单02...', times: '3h', status: WorkStatus.COMPLETED },
        { id: 'Wed-3', type: 'Work', title: 'Wed-测试工单03', content: '1.测试工单03...', times: '--', status: WorkStatus.PENDING }
      ],
    },
    {
      id: "Thu",
      title: "周四",
      accepts: ["Work"],
      items: [
        { id: 'Thu-1', type: 'Work', title: 'Thu-测试工单01', content: '1.测试工单01...', times: '2h', status: WorkStatus.INPROGRESS },
        { id: 'Thu-2', type: 'Work', title: 'Thu-测试工单02', content: '1.测试工单02...', times: '3h', status: WorkStatus.COMPLETED },
        { id: 'Thu-3', type: 'Work', title: 'Thu-测试工单03', content: '1.测试工单03...', times: '--', status: WorkStatus.PENDING }
      ],
    },
    {
      id: "Fri",
      title: "周五",
      accepts: ["Work"],
      items: [
        { id: 'Fri-1', type: 'Work', title: 'Fri-测试工单01', content: '1.测试工单01...', times: '2h', status: WorkStatus.INPROGRESS },
        { id: 'Fri-2', type: 'Work', title: 'Fri-测试工单02', content: '1.测试工单02...', times: '3h', status: WorkStatus.COMPLETED },
        { id: 'Fri-3', type: 'Work', title: 'Fri-测试工单03', content: '1.测试工单03...', times: '--', status: WorkStatus.PENDING }
      ],
    },
    {
      id: "Sat",
      title: "周六",
      accepts: ["Work"],
      items: [
        { id: 'Sat-1', type: 'Work', title: 'Sat-测试工单01', content: '1.测试工单01...', times: '2h', status: WorkStatus.INPROGRESS },
        { id: 'Sat-2', type: 'Work', title: 'Sat-测试工单02', content: '1.测试工单02...', times: '3h', status: WorkStatus.COMPLETED },
        { id: 'Sat-3', type: 'Work', title: 'Sat-测试工单03', content: '1.测试工单03...', times: '--', status: WorkStatus.PENDING }
      ],
    },
    {
      id: "Sun",
      title: "周日",
      accepts: ["Work"],
      items: [],
    }
  ]
const useWorkDrag = () => {
  const [containers, setContainers] = useState<Container[]>([
        {
      id: "Mon",
      title: "周一",
      accepts: ["Work"],
      items: [],
    },
    {
      id: "Tue",
      title: "周二",
      accepts: ["Work"],
      items: [],
    },
    {
      id: "Wed",
      title: "周三",
      accepts: ["Work"],
      items: [],
    },
    {
      id: "Thu",
      title: "周四",
      accepts: ["Work"],
      items: [],
    },
    {
      id: "Fri",
      title: "周五",
      accepts: ["Work"],
      items: [],
    },
    {
      id: "Sat",
      title: "周六",
      accepts: ["Work"],
      items: [],
    },
    {
      id: "Sun",
      title: "周日",
      accepts: ["Work"],
      items: [],
    }
  ])
  const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
  const sensors = useSensors(useSensor(PointerSensor))
  // 获取当前激活的元素
  const activeItem = containers
    .flatMap((c) => c.items)
    .find((item) => item.id === activeId)

  // 拖拽开始
  const handleDragStart = ({ active }: DragStartEvent) => {
    setActiveId(active.id);
  }
  // 拖拽结束（核心逻辑）
  const handleDragEnd = useCallback(({ active, over }: DragEndEvent) => {
    if (!over) {
      setActiveId(null);
      return;
    }

    // 获取源容器和目标容器
    const activeContainer = containers.find((c) =>
      c.items.some((i) => i.id === active.id)
    );
    const overContainer = containers.find((c) =>
      c.items.some((i) => i.id === over.id)
    ) || containers.find((c) => c.id === over.id); // 可能拖到空白容器区域

    if (!activeContainer || !overContainer) return;

    // 获取拖拽元素
    const activeItem = activeContainer.items.find((i) => i.id === active.id);
    if (!activeItem) return;

    // 校验类型是否匹配
    if (!overContainer.accepts.includes(activeItem.type)) {
      setActiveId(null);
      return; // 阻止拖拽
    }

    // 同一容器内排序
    if (activeContainer.id === overContainer.id) {
      
      // const oldIndex = activeContainer.items.findIndex((i) => i.id === active.id);
      // const newIndex = activeContainer.items.findIndex((i) => i.id === over.id);
      // // console.log('oldIndex', oldIndex)
      // // console.log('newIndex', newIndex)
      // setContainers(
      //   containers.map((c) =>
      //     c.id === activeContainer.id
      //       ? {
      //         ...c,
      //         items: arrayMove(c.items, oldIndex, newIndex),
      //       }
      //       : c
      //   )
      // );
    } else {
      // 跨容器移动
      const activeIndex = activeContainer.items.findIndex((i) => i.id === active.id);
      const overIndex = overContainer.items.length + 1; // 插入位置

      setContainers(
        containers.map((c) => {
          if (c.id === activeContainer.id) {
            return {
              ...c,
              items: c.items.filter((i) => i.id !== active.id), // 从源容器移除
            };
          } else if (c.id === overContainer.id) {
            return {
              ...c,
              items: [
                ...c.items.slice(0, overIndex),
                activeItem,
                ...c.items.slice(overIndex),
              ], // 插入目标容器
            };
          }
          return c;
        })
      );
    }
    setActiveId(null);
  }, [containers])
  // 拖拽动画配置
  const dropAnimation: DropAnimation = {
    ...defaultDropAnimation,
  }
  // 设置数据
  const setWorks = (data: any[]) => {
    const _data = DATA.map((d,index)=>{
      return {
        ...d,
        date: data[index]
      }
    })
    setContainers(_data)
  }
  return {
    containers,
    sensors,
    handleDragStart,
    handleDragEnd,
    dropAnimation,
    activeItem,
    setWorks
  }
}

export default useWorkDrag